package com.fivefu.core.hillstone.services.impl;

import com.alibaba.fastjson.JSON;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hillstone.dto.request.*;
import com.fivefu.core.hillstone.dto.response.DeviceChannelDto;
import com.fivefu.core.hillstone.dto.response.OrganizationDto;
import com.fivefu.core.hillstone.dto.response.OrganizationPageDto;
import com.fivefu.core.hillstone.entity.DbHillstoneChannel;
import com.fivefu.core.hillstone.entity.DbHillstoneDevice;
import com.fivefu.core.hillstone.entity.DbHillstoneOrganization;
import com.fivefu.core.hillstone.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private HillstoneService hillstoneService;
    @Autowired
    private DbHillstoneOrganizationService dbHillstoneOrganizationService;

    @Autowired
    private DbHillstoneChannelService channelService;

    @Autowired
    private DbHillstoneChannelAbilityService channelAbilityService;

    @Autowired
    private DbHillstoneDeviceService deviceService;

    @Autowired
    private DbHillstoneOrganizationDeviceService organizationDeviceService;

    /**
     *
     * @param organizationId
     */
    public void queryOrganizaitonList(String organizationId) {
        //大华查询结果
        List<OrganizationDto> orgList = queryOrganization(1,organizationId);
        for (OrganizationDto org : orgList){
            DbHillstoneOrganization organization = org.formatHillstoneOrganization();
            //删除本地多余组织数据信息
            dbHillstoneOrganizationService.deleteRedundantData(organization.getOrgCode());

            dbHillstoneOrganizationService.editHillstoneOrganization(organization);

            queryOrganizaitonList(org.getId());
        }
    }


    /**
     * 分页查询组织架构
     * @param pageNo
     */
    @Override
    public List<OrganizationDto> queryOrganization(Integer pageNo, String organizationId){
        List<OrganizationDto> orgIDs = new ArrayList<>();
        OrganizationPageQueryDto dto = new OrganizationPageQueryDto();
        dto.setPage(pageNo);
        dto.setPageSize(1000);
        dto.setNodeType(1);
        dto.setTypeCode("01");
        dto.setId(organizationId);

        String result = hillstoneService.getHillstone("/videoService/devicesManager/deviceTree" + dto.getParam());
        if (StrUtils.isNotNull(result) && !result.equals("error")){
            OrganizationPageDto pageDto = JSON.parseObject(result, OrganizationPageDto.class);

            List<OrganizationDto> array = JSON.parseArray(pageDto.getResults(), OrganizationDto.class);
            array.forEach(org -> {
                String id = org.getId();
                orgIDs.add(org);
            });

            if(pageDto.getNextPage() > 0){
                orgIDs.addAll(queryOrganization(pageNo + 1, organizationId));
            }

            //System.out.println(pageDto.getResults());
        }
        return orgIDs;
    }

    /**
     * 分页获取通道设备
     */
    @Override
    public void getChannelDevices() {
        //查询本地组织架构表获取组织编码
        List<DbHillstoneOrganization> organizationList = dbHillstoneOrganizationService.queryAll();
        if (null != organizationList && organizationList.size() > 0) {
            for (DbHillstoneOrganization organization : organizationList) {
                List<DeviceChannelDto> deviceChannelList = queryChannelDevices(1,organization.getOrgCode());
                for (DeviceChannelDto deviceChannelDto : deviceChannelList) {
                    //判断节点类型nodeType
                    if (2 == deviceChannelDto.getNodeType()) {//设备
                        DbHillstoneDevice device = deviceChannelDto.formatDbHillstoneDevice();
                        //删除本地多余设备数据信息
                        deviceService.deleteRedundantData(device.getDeviceCode());
                        //编辑设备信息
                        deviceService.editDbHillstoneDevice(device);
                        //删除多余组织设备关联数据信息
                        organizationDeviceService.deleteRedundantData(deviceChannelDto.getOrgCode(),deviceChannelDto.getDeviceId());
                        //编辑组织设备关联表
                        organizationDeviceService.editDbHillstoneOrganizationDevice(deviceChannelDto.getOrgCode(),deviceChannelDto.getDeviceId());
                    } else if (3 == deviceChannelDto.getNodeType()) {//通道
                        DbHillstoneChannel channel = deviceChannelDto.formatDbHillstoneChannel();
                        //删除本地多余通道数据
                        channelService.deleteRedundantData(channel.getChannelCode());
                        //编辑通道信息
                        channelService.editDbHillstoneChannel(channel);
                        //编辑通道能力关联表
                        channelAbilityService.editChannelAbility(deviceChannelDto.getChannelId(),deviceChannelDto.getCameraFunctions());
                        //删除多余组织设备关联数据信息
                        organizationDeviceService.deleteRedundantData(deviceChannelDto.getOrgCode(),deviceChannelDto.getDeviceId());
                        //编辑组织设备关联表
                        organizationDeviceService.editDbHillstoneOrganizationChannel(deviceChannelDto.getOrgCode(),deviceChannelDto.getChannelId(),deviceChannelDto.getDeviceCode());
                    }
                }
            }
        }
    }

    /**
     * 分页获取通道设备
     * @param pageNo           页码
     * @param organizationId   组织的唯一编码
     * @return
     */
    private List<DeviceChannelDto> queryChannelDevices(Integer pageNo, String organizationId) {
        List<DeviceChannelDto> deviceChannelList = new ArrayList<>();
        OrganizationPageQueryDto dto = new OrganizationPageQueryDto();
        dto.setPage(pageNo);
        dto.setPageSize(1000);
        dto.setNodeType(1);
        dto.setTypeCode("01;1;ALL;ALL");//检索类型
        dto.setId(organizationId);
        String result = hillstoneService.getHillstone("/videoService/devicesManager/deviceTree" + dto.getParam());

        if (StrUtils.isNotNull(result) && !result.equals("error")) {
            OrganizationPageDto pageDto = JSON.parseObject(result, OrganizationPageDto.class);

            List<DeviceChannelDto> array = JSON.parseArray(pageDto.getResults(), DeviceChannelDto.class);
            array.forEach(deviceChannelDto -> {
                deviceChannelList.add(deviceChannelDto);
            });

            if(pageDto.getNextPage() > 0){
                deviceChannelList.addAll(queryChannelDevices(pageNo + 1, organizationId));
            }
        }
        return deviceChannelList;
    }

    /**
     * 分页获取通道设备       (汇总用的)
     * @param pageNo          页码
     * @param organizationId  组织的唯一编码
     * @param type            检索类型  查询设备：01;1;ALL    仅查询通道：01;0;ALL;ALL
     * @return
     */
    @Override
    public List<DeviceChannelDto> onlyQueryChannelDevices(Integer pageNo, String organizationId,String type) {
        List<DeviceChannelDto> deviceChannelList = new ArrayList<>();
        OrganizationPageQueryDto dto = new OrganizationPageQueryDto();
        dto.setPage(pageNo);
        dto.setPageSize(1000);
        dto.setNodeType(1);
        dto.setTypeCode(type);//检索类型
        dto.setId(organizationId);
        String result = hillstoneService.getHillstone("/videoService/devicesManager/deviceTree" + dto.getParam());

        if (StrUtils.isNotNull(result) && !result.equals("error")) {
            OrganizationPageDto pageDto = JSON.parseObject(result, OrganizationPageDto.class);

            List<DeviceChannelDto> array = JSON.parseArray(pageDto.getResults(), DeviceChannelDto.class);
            array.forEach(deviceChannelDto -> {
                deviceChannelList.add(deviceChannelDto);
            });

            if(pageDto.getNextPage() > 0){
                deviceChannelList.addAll(onlyQueryChannelDevices(pageNo + 1, organizationId,type));
            }
        }
        return deviceChannelList;
    }

    /**
     * 完善设备节点信息
     */
    @Override
    public void queryEquipmentInfoByDeviceCode() {
        deviceService.queryEquipmentInfoByDeviceCode();
    }
}
